package cz.data.common.feign.interceptor;

import cz.data.common.annotation.DataInner;
import cz.data.common.support.security.DiscoveryServiceHeaderFactory;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class DataInnerRequestInterceptor implements RequestInterceptor {
    private static final Map<Method, Boolean> INNER_METHOD = new ConcurrentHashMap<>();
    private final DiscoveryServiceHeaderFactory factory;

    public DataInnerRequestInterceptor(DiscoveryServiceHeaderFactory factory) {
        this.factory = factory;
    }


    @Override
    public void apply(RequestTemplate requestTemplate) {
        Method method = requestTemplate.methodMetadata().method();
        if (isDataInnerPresent(method)) {
            Map<String, String> headers = factory.headers();
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestTemplate.removeHeader(entry.getKey());
                requestTemplate.header(entry.getKey(), entry.getValue());
            }
        }
    }

    private boolean isDataInnerPresent(Method method) {
        Boolean value = INNER_METHOD.get(method);
        if (Objects.isNull(value)) {
            value = method.isAnnotationPresent(DataInner.class);
            INNER_METHOD.put(method, value);
        }
        return value;
    }
}
